package com.jctf.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Sequence2 implements MessageListener {

	private NetworkManager n;
	private static int PORT = 33962;
	
	public static void main(String[] args) {
		try {
			new Sequence2().run();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void run() throws InterruptedException, IOException, ClassNotFoundException {
		System.out.println("Starting Sequence 2. Initializing networking...");
		n = new NetworkManager("spoon.dontexist.com", PORT);
		n.registerMessageListener(this);
		n.start();
		int num = 1;
		while(num < 100) {
			n.sendMessage(new NumberMessage(num));
			n.flush();
			Thread.sleep(50);
			num += 2;	
		}
		System.out.println("Quitting...");
		n.close();
	}

	@Override
	public void messageReceived(Message message) {
		System.out.println("Message received: " + message);
	}

	private class NetworkManager extends NetworkHandler {

		private String server;
		private int port;
		private Socket connection;
		private ObjectInputStream input;
		private ObjectOutputStream output;
		
		public NetworkManager(String serverAddress, int portNumber) {
			server = serverAddress;
			port = portNumber;
		}

		public void start() throws IOException, ClassNotFoundException {
			// block for connection
			connection = new Socket(server, port);
			System.out.println("Connected to server.");
			output = new ObjectOutputStream(connection.getOutputStream());
			output.flush();
			input = new ObjectInputStream(connection.getInputStream());
			System.out.println("Extracted streams.");
			System.out.println("Attempting login...");
			output.writeObject(new RequestLoginMessage("username1", "password1"));
			output.flush();
		}
		
		public void close() throws IOException {
			connection.close();
		}
		
		public void sendMessage(Message m) throws IOException {
			output.writeObject(m);
		}

		public void registerMessageListener(MessageListener l) {
			listeners.add(l);
			System.out.println("Sequence 2 added as a listener.");
		}

		public void flush() throws IOException {
			output.flush();
		}
		
	}

}
